package com.chat.mapper;

import com.chat.entry.dto.group.ReadAllMessageDTO;
import com.chat.entry.dto.group.ReadSingleMessageDTO;
import com.chat.entry.po.GroupMessageUnread;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.chat.entry.vo.group.GroupMessageWithUnreadVO;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * <p>
 * 群未读表 Mapper 接口
 * </p>
 *
 * @author author
 * @since 2025-09-14
 */
public interface GroupMessageUnreadMapper extends BaseMapper<GroupMessageUnread> {

    void insertBatch(List<GroupMessageUnread> groupMessageUnreads);

    @Select("SELECT gmu.id AS groupMessageUnreadId, gm.id AS messageId, gm.group_id, gm.sender_id, gm.content, gm.type, gm.create_time AS sendTime, " +
            "gmu.receiver, gmu.read_status " +
            "FROM group_message_unread gmu " +
            "JOIN group_message gm ON gmu.message_id = gm.id " +
            "WHERE gmu.receiver = #{userId} " +
            "AND gm.group_id = #{groupId} " +
            "AND gmu.read_status = 0 " +
            "ORDER BY gm.id DESC LIMIT 20")
    List<GroupMessageWithUnreadVO> selectMessagesWithUnread(ReadSingleMessageDTO dto);

    @Update("UPDATE group_message_unread gmu " +
            "JOIN group_message gm ON gmu.message_id = gm.id " +
            "SET gmu.read_status = 1 , gmu.read_time = NOW() " +
            "WHERE gmu.receiver = #{userId} " +
            "AND gmu.read_status = 0 " +
            "AND gm.group_id = #{groupId}")
    int readAllGroupChatMessage(ReadAllMessageDTO dto);

    @Update("UPDATE group_message_unread gmu " +
            "SET gmu.read_status = 1 , gmu.read_time = NOW() " +
            "WHERE gmu.receiver = #{userId} AND gmu.read_status = 0")
    int updateAllGroupMessages(Integer userId);
}
